/*! \page license
 *
 * Copyright (c) 2011, Blaise Lengrand
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list
 * of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this
 * list of conditions and the following disclaimer in the documentation and/or
 * other materials provided with the distribution.
 * Neither the name of `snWin' nor the names of its contributors may be used to
 * endorse or promote products derived from this software without specific prior
 * written permission.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
/*! \file
 * \brief Set of helper functions to get or post to URLs
 */

/*! Send a GET request to an URL and returns the json formated result
 */
function feed_get_json(feed_id, url, on_success, on_error)
{
  $.ajax({
    url: url,
    dataType: 'json',
    error: function(xhr, status, error) {
      // Test if the callback is called
      feed_callback.is_called = false;
      try
      {
        error = eval("(" + xhr.responseText + ")");
        error = error.Message;
      }
      catch(e)
      {
        error = xhr.responseText;
      }
      feed_log("Error `" + error + "'", feed_id, "error");
      if (typeof on_error != "undefined")
        on_error();
      if (!feed_callback.is_called)
        feed_callback(feed_id, true);
    },
    success: function(data, status, xhr) {
      // Test if the callback is called
      feed_callback.is_called = false;
      if (typeof on_success != "undefined")
        on_success(data);
      if (!feed_callback.is_called)
        feed_callback(feed_id);
    }
  });
}

/*! Send a POST request to an URL and returns the result
 */
function feed_post(feed_id, url, data, on_success, on_error)
{
  $.ajax({
    type: "POST",
    url: url,
    data: data,
    error: function(xhr, status, error) {
      // Test if the callback is called
      feed_callback.is_called = false;
      feed_log("Error " + xhr.status  + " - `" + xhr.responseText + "'", feed_id, "error");
      if (typeof on_error != "undefined")
        on_error();
      if (!feed_callback.is_called)
        feed_callback(feed_id, true);
    },
    success: function(data, status, xhr) {
      // Test if the callback is called
      feed_callback.is_called = false;
      if (typeof on_success != "undefined")
        on_success(data);
      if (!feed_callback.is_called)
        feed_callback(feed_id);
    }
  });
}

/*! Encode a string using HTML entities
 */
function feed_html_encode(value)
{
  return $('<div/>').text(value).html();
}

/*! Decode a string previously encoded by \ref feed_html_encode
 */
function feed_html_decode(value)
{
  return $('<div/>').html(value).text();
}

/*! Format a string to fit inside brackets ("").
 */
function feed_to_cstr(str)
{
  str = str.replace(/\\/g, '\\\\');
  str = str.replace(/\'/g, '\\\'');
  str = str.replace(/\"/g, '\\"');
  str = str.replace(/\0/g, '\\0');
  str = str.replace(/\n/g, '\\n');
  str = str.replace(/\t/g, '\\t');
  str = str.replace(/\r/g, '\\r');
  return str;
}

/*! This function removes all the html tags from a string
 */
function feed_to_multiline_text(str)
{
  // Remove all new lines
  str = str.replace(/[\n\t\r\0\v\s]+/g, " ");
  str = str.replace(/<br/gi, '\n<br');
  str = str.replace(/<tr/gi, '\n<tr');
  // Convert html to text
  str = $('<div/>').html(str).text();
  // Do not allow multiple new lines
  str = str.replace(/\n(\s*\n)+/g, "\n");
  // Remove \n if at the begning of the string
  str = str.replace(/^\s*\n/, "");
  return str;
}

/*! This functon removes all html tags from a string and make this string single line.
 */
function feed_to_text(str)
{
  str = $('<div/>').html(str).text();
  str = str.replace(/[\n\t\r\0\v\s]+/g, " ");
  return str;
}

/*! This function returns the host URL
 */
function feed_host_url()
{
  var parsed_url = $.url.parse(document.location.href);
  var built_url = $.url.build({
    "protocol": (parsed_url.protocol)?parsed_url.protocol:"http",
    "host": parsed_url.host,
    "port": (parsed_url.port)?parsed_url.port:null,
    "path": parsed_url.path,
  });
  return built_url;
}

/*! This function is used to identify a link inside a string
 * \param str The string
 * \return the link, or null if no link is found.
 */
function feed_find_link(str)
{
  // Strips the tags
  var text = feed_to_text(str);
  // http://xxx or ftp://xxx types
  var exp = /(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/ig;
  var link = text.match(exp);
  if (!link)
  {
    // www.xxx
    exp = /(www\.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]/ig;
    link = text.match(exp)
  }
  return (link)?link[0]:null;
}
